<?php

namespace app\admin\controller;

use app\common\Helper;

use app\admin\model\Operator;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 管理员
 */
class Admin extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new Operator();
    }

    /**
     * 列表
     */
    public function getList(){
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $defaultWhere = $this->getDefaultWhere();
        if($this->admin->roleType != 1){
            $defaultWhere['createOper'] = $this->admin->id;
        }
        $where = $defaultWhere;
        $model = $this->model;
        $order = 'createDate DESC';
        $result = $model->where($where)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关账号');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 添加/编辑 保存
     */
    public function save(){
        $param = self::getHttpParam();
        $model = $this->model;

        /*if (empty($param->name)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'name 不能为空');
        }*/
        if (empty($param->loginName)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'loginName 不能为空');
        }
        if (empty($param->password)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'password 不能为空');
        }
        if (empty($param->phone)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'phone 不能为空');
        }
        if (empty($param->remark)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'remark 不能为空');
        }
        /*if (empty($param->ruleIds)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'ruleIds 不能为空');
        }*/
        /*if (empty($param->province)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'province 不能为空');
        }*/
        /*if (empty($param->city)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'city 不能为空');
        }*/

        $data = (array)$param;
        $data['password'] = Helper::passwordEncrypt($param->password);

        Db::startTrans();
        try {
            $id = '';
            if(!empty($param->id)){
                $id = $param->id;
            }
            if(!$this->checkLoginName($param->loginName, $id)){
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '该登录名已存在！');
            }
            if (!empty($param->id)) {
                // 修改
                $data['id'] = $param->id;
                $data['updateDate'] = date('Y-m-d H:i:s');
                $data['updateOper'] = $this->admin->id;
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                // Query执行后的操作
                $model->_after_update($data);
            } else {
                // 新增
                $data['id'] = Helper::getUUID();
                $data['createDate'] = date('Y-m-d H:i:s');
                $data['createOper'] = $this->admin->id;
                $data['roleType'] = 2;
                $result = $model->save($data);

                // Query执行后的操作
                $model->_after_insert($data);
            }

            if($result !== false){
                $operatormoduleDB = db('operatormodule');
                // 删除旧的权限
                $operatormoduleDB->where('operateId', $data['id'])->delete();
                //$ids = explode(',', $param->ruleIds);
                $ids = $param->ruleIds;
                $data2 = [];
                foreach ($ids as $key => $id) {
                    $data2['operateId'] = $data['id'];
                    $data2['moduleId'] = $id;
                    // 添加新的权限
                    $res = $operatormoduleDB->insert($data2);
                    if($res === false){
                        Db::rollback();
                        return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
                    }
                }

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '保存成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 删除
     */
    public function delete(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $id = $param->id;
        Db::startTrans();
        try {
            //$result = $model->where('id', $id)->delete();
            $result = db('operatormodule')->where('operateId', $id)->delete();
            if($result !== false){
                //$res = db('operatormodule')->where('operateId', $id)->delete();
                $res = $model->where('id', $id)->delete();
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
                }

                // Query执行后的操作
                $model->_after_delete($id);

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '删除成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 获取权限
     */
    public function getRule(){
        $param = self::getHttpParam();
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $id = $param->userId;
        $adminInfo = Operator::where(['id' => $id])->find();
        // 管理员权限
        // 是否是超级管理员
        if($adminInfo['roleType'] == 1){
            $options = db('module')
                ->where(['isActive' => 1, 'status' => 1])
                ->field('id as moduleId, name')
                ->select();
        }else{
            $options = db('operatormodule')
                ->alias('a')
                ->where(['a.operateId' => $adminInfo['id']])
                ->join('__MODULE__ m', 'm.id = a.moduleId')
                ->field('a.moduleId, m.name')
                ->select();
        }

        /*$where = [
            'isActive' => 1
        ];
        $options = db('module')->where($where)->field('id,name')->select();*/

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $options);
    }

    private function checkLoginName($loginName, $id)
    {
        $model = $this->model;

        if ($id) {
            $info = $model->where(['id' => $id])->field('loginName')->find();
            if($info['loginName'] != $loginName){
                $result = $model->where(['loginName' => $loginName])->field('loginName')->find();
                if(!$result){
                    return true;
                }
            }else{
                return true;
            }
        } else {
            $result = $model->where(['loginName' => $loginName])->field('loginName')->find();
            if(!$result){
                return true;
            }
        }

        return false;
    }

}